<template>
  <div class="template-canvas-container">
    <el-page-header :content="`模板编辑：${templateId}`"></el-page-header>
    <!-- 工具栏 -->
    <tool-bar
      :selected-cell="selectedCell"
      @merge-cell="handleMergeCell"
      @split-cell="handleSplitCell"
      @add-row="handleAddRow"
      @add-col="handleAddCol"
      @open-param-selector="openParamSelector"
      @add-signature="handleAddSignature"
      @preview="handlePreview"
      @export-excel="handleExportExcel"
      @save-template="handleSaveTemplate"
    ></tool-bar>
    <!-- 画布主体 -->
    <div class="canvas-wrapper">
      <div class="canvas-content" :style="{ width: canvasWidth + 'px' }">
        <el-table
          :data="tableData"
          :span-method="objectSpanMethod"
          border
          style="width: 100%; table-layout: fixed"
          @cell-click="handleCellClick"
          @cell-mouse-enter="handleCellMouseEnter"
        >
          <el-table-column
            v-for="col in colList"
            :key="col.col"
            :label="`列${col.col}`"
            :width="col.width || 120"
          >
            <template #default="scope">
              <div class="cell-content">
                {{ getCellContent(scope.row.row, col.col) }}
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 动态添加的签字栏组件 -->
        <SignatureField
          v-for="(item, index) in signatureList"
          :key="index"
          :style="{left: item.x + 'px',top: item.y + 'px',position: 'absolute'}"
          :name="item.name"
        ></SignatureField>
      </div>
    </div>
    <!-- 参数选择器弹窗 -->
    <param-selector
      ref="paramSelector"
      :current-cell="selectedCell"
      @associate-success="handleAssociateSuccess"
    ></param-selector>
    <!-- 预览弹窗 -->
    <el-dialog
      title="模板预览"
      :visible.sync="previewVisible"
      width="80%"
      append-to-body
    >
      <div class="preview-container">
        <el-table
          :data="previewTableData"
          :span-method="previewSpanMethod"
          border
          style="width: 100%"
        >
          <el-table-column
            v-for="col in colList"
            :key="col.col"
            :label="`列${col.col}`"
            :width="col.width || 120"
          >
            <template #default="scope">
              {{ getPreviewCellContent(scope.row.row, col.col) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ToolBar from './ToolBar'
import ParamSelector from '../param-selector/ParamSelector'
import SignatureField from '../common/SignatureField'
import { excelExportUtil } from '@/utils/excelUtil'

export default {
  name: 'TemplateCanvas',
  components: { ToolBar, ParamSelector, SignatureField },
  props: {
    templateId: {
      type: String,
      required: true
    },
    parseResult: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      // 解析后的基础数据
      cells: [], // 单元格列表
      merges: [], // 合并规则
      // 画布配置
      colList: [], // 列列表（col: 列号, width: 宽度）
      tableData: [], // 表格行数据
      canvasWidth: 1200,
      // 选中状态
      selectedCell: null, // 当前选中单元格 {row, col}
      // 关联规则
      paramAssociateRules: [], // 参数关联规则
      // 动态添加元素
      signatureList: [], // 签字栏列表
      // 预览相关
      previewVisible: false,
      previewTableData: []
    }
  },
  mounted() {
    this.initCanvas()
  },
  methods: {
    // 初始化画布
    initCanvas() {
      const { cells, merges } = this.parseResult
      // 初始化单元格和合并规则
      this.cells = JSON.parse(JSON.stringify(cells))
      this.merges = JSON.parse(JSON.stringify(merges))
      // 生成列列表
      this.generateColList()
      // 生成表格行数据
      this.generateTableData()
    },
    // 生成列列表
    generateColList() {
      const colSet = new Set(this.cells.map((cell) => cell.col))
      this.colList = Array.from(colSet)
        .sort((a, b) => a - b)
        .map((col) => ({
          col,
          width: 120 // 默认列宽
        }))
      // 计算画布宽度
      this.canvasWidth = this.colList.reduce(
        (total, col) => total + (col.width || 120),
        40
      )
    },
    // 生成表格行数据
    generateTableData() {
      const maxRow = Math.max(...this.cells.map((cell) => cell.row))
      this.tableData = Array.from({ length: maxRow }, (_, index) => ({
        row: index + 1
      }))
    },
    // 表格合并单元格方法
    objectSpanMethod({ row, column }) {
      const currentRow = row.row
      const currentCol = column.index + 1 // 列索引0→1
      const merge = this.merges.find(
        (m) => m.row === currentRow && m.col === currentCol
      )
      if (merge) {
        return {
          rowspan: merge.rowspan,
          colspan: merge.colspan
        }
      }
      return { rowspan: 1, colspan: 1 }
    },
    // 获取单元格内容（编辑模式）
    getCellContent(row, col) {
      // 先查找参数关联规则
      const associateRule = this.paramAssociateRules.find(
        (rule) => rule.cellRow === row && rule.cellCol === col
      )
      if (associateRule) {
        return `{{${associateRule.headerName}}}`
      }
      // 再查找固定文本
      const cell = this.cells.find((c) => c.row === row && c.col === col)
      return cell ? cell.value : ''
    },
    // 单元格点击事件
    handleCellClick(row, column) {
      this.selectedCell = {
        row: row.row,
        col: column.index + 1
      }
    },
    // 单元格鼠标悬浮事件（高亮合并区域）
    handleCellMouseEnter(row, column) {
        console.log(row, column)
      // 可扩展：高亮当前单元格所在的合并区域
    },
    // 打开参数选择器
    openParamSelector() {
      this.$refs.paramSelector.open()
    },
    // 参数关联成功
    handleAssociateSuccess(rule) {
      // 多测量点处理：自动关联后续列
      if (rule.isMultiMeasure && rule.associateAllMeasures) {
        for (let i = 0; i < rule.multiMeasureCount; i++) {
          const associateRule = {
            ...rule,
            cellCol: rule.cellCol + i,
            headerName: `${rule.headerName}-${i + 1}`
          }
          this.paramAssociateRules.push(associateRule)
          // 自动新增列（如果列不存在）
          this.addColIfNotExist(rule.cellCol + i)
        }
      } else {
        this.paramAssociateRules.push(rule)
      }
      this.$message.success('参数关联成功')
    },
    // 合并单元格
    handleMergeCell() {
      if (!this.selectedCell) {
        this.$message.warning('请先选中要合并的单元格')
        return
      }
      // 简化逻辑：合并当前单元格和右侧1列（实际可扩展多选）
      const { row, col } = this.selectedCell
      const targetCol = col + 1
      // 检查目标列是否存在
      const targetColExist = this.colList.some((c) => c.col === targetCol)
      if (!targetColExist) {
        this.$message.warning('目标列不存在，请先新增列')
        return
      }
      // 检查是否已合并
      const isMerged = this.merges.some(
        (m) => m.row === row && m.col === col && m.colspan >= 2
      )
      if (isMerged) {
        this.$message.warning('该单元格已合并，请勿重复操作')
        return
      }
      // 添加合并规则
      this.merges.push({
        row,
        col,
        rowspan: 1,
        colspan: 2
      })
      this.$message.success('单元格合并成功')
    },
    // 拆分单元格
    handleSplitCell() {
      if (!this.selectedCell) {
        this.$message.warning('请先选中要拆分的单元格')
        return
      }
      const { row, col } = this.selectedCell
      // 查找当前单元格的合并规则
      const mergeIndex = this.merges.findIndex(
        (m) =>
          m.row === row && m.col === col && (m.rowspan > 1 || m.colspan > 1)
      )
      if (mergeIndex === -1) {
        this.$message.warning('该单元格未合并，无法拆分')
        return
      }
      // 删除合并规则
      this.merges.splice(mergeIndex, 1)
      this.$message.success('单元格拆分成功')
    },
    // 新增行
    handleAddRow() {
      const maxRow = Math.max(...this.cells.map((cell) => cell.row))
      const newRow = maxRow + 1
      // 新增空单元格
      this.colList.forEach((col) => {
        this.cells.push({
          row: newRow,
          col: col.col,
          value: '',
          isEmpty: true,
          address: `${String.fromCharCode(64 + col.col)}${newRow}`
        })
      })
      // 刷新表格数据
      this.generateTableData()
      this.$message.success('新增行成功')
    },
    // 新增列
    handleAddCol() {
      const maxCol = Math.max(...this.colList.map((col) => col.col))
      this.addColIfNotExist(maxCol + 1)
    },
    // 新增列（如果不存在）
    addColIfNotExist(col) {
      const colExist = this.colList.some((c) => c.col === col)
      if (!colExist) {
        this.colList.push({ col, width: 120 })
        // 为每一行新增空单元格
        const maxRow = Math.max(...this.cells.map((cell) => cell.row))
        for (let row = 1; row <= maxRow; row++) {
          this.cells.push({
            row,
            col,
            value: '',
            isEmpty: true,
            address: `${String.fromCharCode(64 + col)}${row}`
          })
        }
        // 刷新画布宽度
        this.canvasWidth = this.colList.reduce(
          (total, c) => total + (c.width || 120),
          40
        )
        this.$message.success(`新增列${col}成功`)
      }
    },
    // 添加签字栏
    handleAddSignature() {
      this.signatureList.push({
        name: `签字栏${this.signatureList.length + 1}`,
        x: 200 + this.signatureList.length * 150,
        y: 300
      })
    },
    // 预览模板
    handlePreview() {
      this.previewTableData = JSON.parse(JSON.stringify(this.tableData))
      this.previewVisible = true
    },
    // 预览表格合并方法
    previewSpanMethod({ row, column }) {
      return this.objectSpanMethod({ row, column })
    },
    // 获取预览单元格内容
    getPreviewCellContent(row, col) {
      const content = this.getCellContent(row, col)
      // 替换占位符为模拟数据
      if (content.startsWith('{{') && content.endsWith('}}')) {
        const paramName = content.slice(2, -2)
        if (paramName.includes('（')) {
          const type = paramName.split('（')[1].replace('）', '')
          if (type === 'kp' || type === '') {
            return (Math.random() * 100).toFixed(1)
          }
          return '模拟文本'
        }
        return (Math.random() * 100).toFixed(1)
      }
      return content
    },
    // 导出Excel
    handleExportExcel() {
      excelExportUtil.exportExcel({
        fileName: `模板_${this.templateId}.xlsx`,
        cells: this.cells,
        merges: this.merges,
        paramAssociateRules: this.paramAssociateRules,
        colList: this.colList
      })
    },
    // 保存模板
    handleSaveTemplate() {
      // 模拟保存（实际项目中提交至后端存储）
      const templateData = {
        templateId: this.templateId,
        cells: this.cells,
        merges: this.merges,
        paramAssociateRules: this.paramAssociateRules,
        signatureList: this.signatureList,
        colList: this.colList
      }
      console.log('模板保存数据：', templateData)
      this.$message.success('模板保存成功')
    }
  }
}
</script>

<style scoped>
.template-canvas-container {
  padding: 20px;
}

.canvas-wrapper {
  padding: 20px;
  background-color: #fff;
  border: 1px solid #e6e6e6;
  margin-top: 10px;
  overflow: auto;
}

.canvas-content {
  position: relative;
}

.cell-content {
  width: 100%;
  height: 100%;
  padding: 4px;
  word-wrap: break-word;
  white-space: normal;
}

.el-table__cell.is-hovered .cell-content {
  background-color: #e6f7ff;
}

.preview-container {
  max-height: 600px;
  overflow: auto;
}
</style>
